package ups.glre.news.webservice.impl;

import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.WebServiceContext;

import ups.glre.news.model.News;
import ups.glre.news.service.NewsService;
import ups.glre.news.webservice.NewsWebService;
import ups.glre.news.webservice.dto.NewsDTO;
import ups.glre.news.webservice.util.Util;

@WebService(name = "NewsWebService")
public class NewsWebServiceImpl implements NewsWebService {
	
	@EJB
	private NewsService newsService;
	
	@Resource
    private WebServiceContext context;
	
	@WebMethod
	@Override
	public void publishNews(NewsDTO news) {
		try {
			newsService.createNews(news.getAuthor(), news.getCategory(), news.getTitle(), news.getContent());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@WebMethod
	@Override
	public List<NewsDTO> getAllNews() {
		List<NewsDTO> newsDTO = new ArrayList<NewsDTO>();
		for (News news : newsService.getAllNews()) {
			newsDTO.add(Util.toDTO(news));
		}
		return newsDTO;
	}
	
	@WebMethod
	@Override
	public List<NewsDTO> getAllNewsAfter(XMLGregorianCalendar xmlCalendar) {
		List<NewsDTO> newsDTO = new ArrayList<NewsDTO>();
		GregorianCalendar calendar = xmlCalendar.toGregorianCalendar();
		for (News news : newsService.getNewsByDate(calendar)) {
			newsDTO.add(Util.toDTO(news));
		}
		return newsDTO;
	}
}